<?php

namespace app\index\controller;

use app\index\model\Goods;
use app\index\model\Order;
use app\index\model\User;
use think\Controller;
use think\Db;
use think\Session;

class Index extends Controller
{
    // 设置批量验证 即遇到一个错误不会马上停止 而是全部都验证一次
    protected $batchValidate = true;

    public function index()
    {
        $list = Goods::paginate(6);
        $page = $list->render();
        return $this->fetch('', ['goodsList' => $list, 'page' => $page]);
    }

    public function classify($type)
    {
        $list = Goods::where('type', $type)->paginate(6);
        $page = $list->render();
        return $this->fetch('index', ['goodsList' => $list, 'page' => $page]);
    }

    public function search()
    {
        $message = $_POST['message'];
        $list = Goods::whereOr('name', 'like', '%' . $message . '%')
            ->whereOr('detail', 'like', '%' . $message . '%')
            ->paginate(6);
        $page = $list->render();
        return $this->fetch('index', ['goodsList' => $list, 'page' => $page, 'oldMessage' => $message]);
    }

    public function login()
    {
        // 使用 Session::flush() 虽然有清除缓存的功能 但是亲测Session还是会存在多一次 所以用delete
        Session::delete('loginErrors');
        Session::delete('loginSuccess');
        $initData = [
            'oldUsername' => null,
            'oldPassword' => null,
        ];
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $result = $this->validate($data, 'app\index\validate\loginValidator');
            $old = [
                'oldUsername' => $data['username'] ? $data['username'] : '',
                'oldPassword' => $data['password'] ? $data['password'] : '',
            ];
            if ($result !== true) {
                Session::flash('loginErrors', $result);
                return $this->fetch('', $old);
            } else {
                $where = [
                    // =号其实可以省略 写成'username' => $data['username']
                    'username' => ['=', $data['username']],
                    'password' => ['=', $data['password']],
                ];
                $user = User::where($where)->find();
                if ($user != null) {
                    Session::set('username', $user->username);
                    Session::set('userId', $user->id);
                    // '/'表示index路由 这里不能写 $this->redirect('index')
                    // 虽然会跳转到index路由但是url变成 www.shop.com/index/index/index
                    // 即把路由给显示出来了
                    $this->success('登录成功', '/');
                } else {
                    Session::flash('loginErrors.username', '用户名或密码有误');
                    Session::flash('loginErrors.password', '用户名或密码有误');
                    return $this->fetch('', $old);
                }
            }
        }
        return $this->fetch('', $initData);
    }

    public function logout()
    {
        Session::delete('userId');
        Session::delete('username');
        $this->success('成功退出', '/');
    }

    public function register()
    {
        // flash的Session虽说只在下次请求前有效 但经过测试还是会多显示一次 手动删除成功信息和输入数据的错误信息Session
        Session::delete('registerSuccess');
        Session::delete('registerErrors');
        // 设置初始数据值 传到模板
        $initData = [
            'oldUsername' => null,
            'oldPassword' => null,
            'oldRepassword' => null,
            'oldPhone' => null,
            'oldAddress' => null,
            'oldBalance' => null,
            'oldPayPassword' => null,
        ];
        // 如果表单提交 即post请求
        if ($this->request->isPost()) {
            $data = $this->request->post();
            // 验证器验证 后面不能实例化 只能写验证器的命名空间
            $result = $this->validate($data, 'app\index\validate\registerValidator');
            $old = [
                'oldUsername' => $data['username'] ? $data['username'] : '',
                'oldPassword' => $data['password'] ? $data['password'] : '',
                'oldRepassword' => $data['repassword'] ? $data['repassword'] : '',
                'oldPhone' => $data['phone'] ? $data['phone'] : '',
                'oldAddress' => $data['address'] ? $data['address'] : '',
                'oldBalance' => $data['balance'] ? $data['balance'] : '',
                'oldPayPassword' => $data['pay_password'] ? $data['pay_password'] : '',
            ];
            if ($result !== true) {
                Session::flash('registerErrors', $result);
                return $this->fetch('', $old);
            } else {
                try {
                    // 后面加个true代表只写入数据表中存在的字段
                    User::create($data, true);
                    $this->success('注册成功', '/');
                } catch (\Exception $e) {
                    if (strpos($e->getMessage(), 'username')) {
                        Session::flash('registerErrors.username', '用户名已存在');
                    } else if (strpos($e->getMessage(), 'phone')) {
                        Session::flash('registerErrors.phone', '手机号已存在');
                    } else {
                        throw $e;
                    }
                    return $this->fetch('', $old);
                }
            }
        }
        return $this->fetch('', $initData);
    }

    public function myDetail()
    {
        if (Session::has('userId')) {
            $data = User::get(Session::get('userId'))->getData();
            $infomation = [
                'username' => $data['username'],
                'phone' => $data['phone'],
                'address' => $data['address'],
                'balance' => $data['balance'],
                'create_time' => $data['create_time'],
                'update_time' => $data['update_time'],
            ];
            return $this->fetch('', $infomation);
        }
        $this->error('请先登录');
    }

    public function myOrder()
    {
        if (Session::has('userId')) {
            $list = Order::where('user_id', Session::get('userId'))->paginate(10);
            foreach ($list as $value) {
                $goods = Goods::get($value['goods_id']);
                $value['goods_picture'] = $goods->getData('picture');
                $value['goods_name'] = $goods->getData('name');
                $value['goods_detail'] = $goods->getData('detail');
            }
            $page = $list->render();
            return $this->fetch('', ['orderList' => $list, 'page' => $page]);
        }
        $this->error('请先登录');
    }

    public function purchase($goodsId)
    {
        $goods = Goods::get($goodsId);
        Session::set('goodsId', $goodsId);
        Session::set('goodsPrice', $goods->getData('price'));
        return $this->fetch('', $goods->getData());
    }

    public function submitOrder()
    {
        if (Session::has('userId')) {
            Session::set('goodsQuantity', $_POST['quantity']);
            $this->redirect('/pay');
        }
        $this->error('请先登录');
    }

    public function pay()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $result = $this->validate($data, 'app\index\validate\payValidator');
            if ($result !== true) {
                Session::flash('payErrors', $result);
            } else {
                if ($data['pay_password'] == User::get(Session::get('userId'))->getData('pay_password')) {
                    if ($this->modifyDB()) {
                        $this->success('购买成功', '/');
                    } else {
                        // 带参数的重定向的两种写法 如果使用传参的参数 则前面要写完整 如果利用路由 则字符串直接加上参数
//                        $this->redirect('index/index/purchase', ['goodsId' => Session::get('goodsId')]);
//                        $this->redirect('/purchase/' . Session::get('goodsId'));
                        // 这里是成功失败的跳转 没有参数提供传参 所以只能手动生成url
                        // 适用所有情况
//                        $this->error('账户余额不足', url('index/index/purchase', 'goodsId=' . Session::get('goodsId')));
                        // 适用定义了路由规则的情况下
                        $this->error('账户余额不足', url('/purchase/' . Session::get('goodsId')));
                    }
                } else {
                    $this->error('支付密码错误');
                }
            }
        }
        return $this->fetch();
    }

    public function receive($orderId)
    {
        Order::update(['order_id' => $orderId, 'status' => '订单已完成']);
        $this->success('收货成功', '/myOrder');
    }

    private function modifyDB()
    {
        $user = User::get(Session::get('userId'));
        $goods = Goods::get(Session::get('goodsId'));
        if ($user->balance >= $goods->price * Session::get('goodsQuantity')) {
            $user->balance = $user->balance - $goods->price * Session::get('goodsQuantity');
            $goods->remain -= Session::get('goodsQuantity');
            $user->isUpdate(true)->save();
            $goods->isUpdate(true)->save();
            $this->createOrder();
            return true;
        }
        return false;
    }

    private function createOrder()
    {
        $data = [
            'goods_id' => Session::get('goodsId'),
            'user_id' => Session::get('userId'),
            'status' => '订单进行中',
            'unit_price' => Session::get('goodsPrice'),
            'quantity' => Session::get('goodsQuantity'),
            'amount' => Session::get('goodsQuantity') * Session::get('goodsPrice'),
        ];
        Order::create($data, true);
    }
}